
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
      >
        <template slot="menuRight">
          <!-- <el-button
            v-if="permissionList.exportGroupLine"
            type="primary"
            size="small"
            hidden = "true"
            @click="openExportDialog(true)"
          >导出（分线路）</el-button> -->
          <el-button
            v-if="false"
            type="primary"
            size="small"
            hidden = "true"
            @click="openExportDialog(true)"
          >导出（分线路）</el-button>
          <el-button
            v-if="permissionList.exportGroupDate"
            type="primary"
            size="small"
            @click="openExportDialog(false)"
          >导出（分日期）</el-button>
        </template>
      </avue-crud>
    </basic-container>

    <!-- 按日期/路线导出 -->
    <el-dialog
      :title="exportByLines ? '按线路导出' : '按日期导出'"
      :visible.sync="dialogFormVisible"
      :destroy-on-close="true"
    >
      <avue-form
        ref="form"
        v-model="form"
        :option="option"
      ></avue-form>
      <el-table
        v-if="exportByLines"
        ref="lineTable"
        :data="lineTableData"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column
          prop="name"
          label="线路"
        > </el-table-column>
      </el-table>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleExport"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchLineList } from "@/api/rca/dict";
import {
  fetchList,
  exportGroupDate,
  exportGroupLine,
} from "@/api/rca/swauinternetticketequipment";
import {
  tableOption,
  defaultStartDate,
  lineTableOption,
  startDate, endDate
} from "@/const/crud/rca/swauinternetticketequipment";
import { mapGetters } from "vuex";
import { handleExcelResponse } from "@/util/util";
import { dateFormat } from "@/util/date";

export default {
  name: "swauinternetticketequipment",
  data () {
    return {
      searchForm: {
        settlementTime: [startDate, endDate]
      },
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,

      // 导出
      lineTableData: [],
      exportByLines: null,
      form: {
        settlementTime: [defaultStartDate, new Date()],
        multipleSelection: [],
      },
      option: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: 120,
        column: [
          {
            type: "daterange",
            label: "结算日期",
            prop: "settlementTime",
            range: true,
            span: 22,
            clearable: false,
            pickerOptions: {
              disabledDate (time) {
                return time.getTime() > Date.now();
              },
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList () {
      return {
        exportGroupLine: this.vaildData(
          this.permissions.sw_au_internet_ticket_equipment_exportGroupLine,
          false
        ),
        exportGroupDate: this.vaildData(
          this.permissions.sw_au_internet_ticket_equipment_exportGroupDate,
          false
        ),
      };
    },

    dialogFormVisible: {
      get () {
        return this.exportByLines !== null;
      },
      set (val) {
        if (val === false) {
          this.closeExportDialog();
        }
      },
    },
  },
  async created () {
    this.loadLines();
  },
  methods: {
    async getList (page, params) {
      this.tableLoading = true;
      const [startDate, endDate] = this.searchForm.settlementTime || [];
      try {
        const response = await fetchList(
          Object.assign(
            {
              current: page.currentPage,
              size: page.pageSize,
            },
            params,
            this.searchForm,
            {
              startDate, endDate
            }
          )
        );
        this.tableData = response.data.data.records;
        this.page.total = response.data.data.total;
        this.tableLoading = false;
      } catch (e) {
        this.tableLoading = false;
      }
    },
    async searchChange (form, done) {
      this.searchForm = { ...form };
      try {
        await this.getList(this.page, form);
      } finally {
        done();
      }
    },
    refreshChange () {
      this.getList(this.page);
    },

    // 弹窗线路
    handleSelectionChange (val) {
      this.form.multipleSelection = val;
    },
    async loadLines () {
      const {
        data: { data },
      } = await fetchLineList(false);
      this.lineTableData = data;
    },
    async openExportDialog (exportByLines = false) {
      this.exportByLines = exportByLines;
    },
    async closeExportDialog () {
      this.exportByLines = null;
      this.form = {
        settlementTime: [defaultStartDate, new Date()],
        multipleSelection: [],
      };
    },
    async handleExport () {
      const { exportByLines, form } = this;
      const { settlementTime, multipleSelection } = form;
      const [startDate, endDate] = settlementTime;

      if (exportByLines) {
        if (multipleSelection.length === 0) {
          this.$message.error("线路不能为空，请指定导出线路");
          return;
        }
        const res = await exportGroupLine({
          startDate: dateFormat(startDate, "yyyy-MM-dd"),
          endDate: dateFormat(endDate, "yyyy-MM-dd"),
          lineCodes: multipleSelection.map((l) => l.code).join(","),
        });
        // handleExcelResponse(res, "按路线导出文件.xlsx");
        handleExcelResponse(res);
        this.dialogFormVisible = false;
      } else {
        const res = await exportGroupDate({
          startDate: dateFormat(startDate, "yyyy-MM-dd"),
          endDate: dateFormat(endDate, "yyyy-MM-dd"),
        });
        // handleExcelResponse(res, "按时间导出文件.xlsx");
        handleExcelResponse(res);
        this.dialogFormVisible = false;
      }
    },
    searchReset () {

      this.page.currentPage = 1
      this.getList(this.page);
    },
  },
};
</script>
